const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
const https = require("https");
const cheerio = require("cheerio")

var reqUrl = "https://maoyan.com/films";
var movieList = [];

http.createServer((req, res) => {
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    if(pathname == "/"){
        var filePath = path.join(__dirname, "/index.html");

        fs.readFile(filePath, (err, data) => {
            if(err){
                console.log(err);
            }
            else{
                res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
                res.write(data);
                res.end();
            }
        });
    }
    else if(pathname == '/getlist'){
        https.get(reqUrl, (resObj) => {
            var htmlStr = "";
            resObj.on("data", (chunk) => {
                htmlStr += chunk;
            })
            resObj.on("end", () => {
                var $ = cheerio.load(htmlStr);
                $(".movie-item-title a").each((i, el) => {
                    var movieName = $(el).text();
                    var movieId = $(el).attr("data-val");
                    movieId = movieId.slice(movieId.indexOf(":")+1, -1);
                    var num1 = $(el).parent().next().children(".integer").text();
                    var num2 = $(el).parent().next().children(".fraction").text();
                    var movieRate = num1 + num2;
                    if(movieRate == ""){
                        movieRate = "暂无评分";
                    }
                    var movieObj = {
                        movieId: movieId,
                        movieName: movieName,
                        movieRate: movieRate
                    }
                    movieList.push(movieObj);
                    console.log(movieObj);
                });

                res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
                res.write(JSON.stringify(movieList));
                res.end();

            })
        })
    }
}).listen(8081);

